package com.jprocms.module.cms.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PdfUtil {

    /**
     * 提取pdf首页作为封面
     *
     * @param pdfFile
     * @param dpi     the DPI (dots per inch) to render at
     * @return
     */
    public static BufferedImage getPdfFirstImage(File pdfFile, float dpi) {
        long startTime = System.currentTimeMillis();
        if (!pdfFile.isFile() || !pdfFile.exists()) {
            return null;
        }
        try (PDDocument document = Loader.loadPDF(pdfFile)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            // 设置页数（首页从0开始）、每英寸点数、图片类型
            BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, dpi, ImageType.RGB);
            log.info("提取耗时：{}ms", System.currentTimeMillis() - startTime);
            return bufferedImage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取pdf的文件内容
     *
     * @param pdfFile
     * @return
     */
    public static String getPdfText(File pdfFile) {
        long startTime = System.currentTimeMillis();
        if (!pdfFile.isFile() || !pdfFile.exists()) {
            return null;
        }
        try (PDDocument document = Loader.loadPDF(pdfFile)) {
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);
            log.info("提取耗时：{}ms", System.currentTimeMillis() - startTime);
            return text;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * pdf 提取封面
     *
     * @param pdfFile pdf文件
     */
    public static void pickupCover(File pdfFile, File targetFile) {
        if (targetFile == null || !targetFile.exists()) {
            targetFile = FileUtil.createTempFile();
        }
        //要渲染的DPI(每英寸点数),可以理解为生成图片的清晰度，值越高生成质量越高
        int dpi = 300;
        try {
            //提取封面工具类
            BufferedImage bufferedImage = PdfUtil.getPdfFirstImage(pdfFile, dpi);
            // 将图片写入到图片文件中
            ImgUtil.write(bufferedImage, targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 加载读取pdf并返回所有的BufferedImage对象
     *
     * @param pdfFile pdf文件对象
     * @param dpi     the DPI (dots per inch) to render at
     * @return
     */
    public static List<BufferedImage> getPdfAllImage(File pdfFile, float dpi) {
        if (!pdfFile.isFile() || !pdfFile.exists()) {
            return null;
        }

        //创建PDFDocument对象并加载PDF文件
        try (PDDocument document = Loader.loadPDF(pdfFile)) {

            //创建一个PDFRenderer对象并将PDDocument对象传递给它
            PDFRenderer pdfRenderer = new PDFRenderer(document);


            List<BufferedImage> bufferedImages = new ArrayList<>();
            BufferedImage bufferedImage;
            for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
                System.out.println("pageIndex:" + pageIndex);
                // 设置页数（首页从0开始）、每英寸点数、图片类型
                bufferedImage = pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB);
                bufferedImages.add(bufferedImage);
            }

            return bufferedImages;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


}
